<template>
  <Dialog width="1000px" :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="scoreFormRef"
      :model="formData"
      label-width="300px"
      v-loading="formLoading"
      label-position="top"
    >
      <div v-for="(item, index) in formData" :key="item.id">
        <p>
          {{index + 1}}. 区域: {{ item.name }}, (总分：{{ item.score }}分),
          <span v-html="item.content"></span>
        </p>
        <div style="margin:20px;">
          <el-radio-group
            v-model="submitFormData[index].areaDetailId"
            @change="updateTotalScore"
          >
            <el-radio border v-for="areaDetail in item.areaDetailDOList" :value="areaDetail.id" :key="areaDetail.id">
              {{ areaDetail.grade }} ({{ areaDetail.score }}分)
            </el-radio>
          </el-radio-group>
        </div>
        <div style="margin:10px;">
          <Editor v-model="submitFormData[index].remark" height="150px" />
        </div>
      </div>
      <p style="font-weight: bold; margin-top: 20px;">
        最终总得分: {{ totalScore }} 分
      </p>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ProjectApi } from '@/api/project/project'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗是否展示
const dialogTitle = ref('') // 弹窗标题
const formLoading = ref(false) // 表单加载状态
const formType = ref('') // 表单类型：create - 新增；update - 修改
const formData = ref<{
  id: number;
  name: string;
  content: string;
  score: number;
  areaDetailDOList: {
    id: number;
    grade: string;
    score: number;
  }[];
}[]>([])

const submitFormData = ref<{
  id: number;
  areaId: number;
  projectId: number;
  assessmentBatchId: number;
  areaDetailId: number | undefined;
  checkType: number;
  remark: string;
}[]>([])

// 用于存储总得分
const totalScore = ref(0)
let allAreaScore = ref(0)
const scoreFormRef = ref()

// 更新总得分逻辑
const updateTotalScore = () => {
  totalScore.value = submitFormData.value.reduce((sum, item, index) => {
    const selectedDetail = formData.value[index]?.areaDetailDOList.find(
      detail => detail.id === item.areaDetailId
    )
    return sum + (selectedDetail?.score || 0)
  }, 0)
}

/** 打开弹窗 */
const open = async (type: string, checkType: number, projectId: number, assessmentBatchId: number) => {

  allAreaScore.value = 0 // bug

  dialogVisible.value = true
  dialogTitle.value = `${t('action.' + type)}打分`
  formType.value = type
  resetForm()
  formLoading.value = true

  // console.log("type", type)
  let preScoreData: any = {};
  if (type === 'update') {
    preScoreData = await ProjectApi.getPreAreaRecord(projectId,checkType,assessmentBatchId)
    console.log('preScoreData', preScoreData)
  }

  try {
    const response = await ProjectApi.getScoreList(checkType)
    formData.value = response || []
    if (formData.value) {
      submitFormData.value = response.map(item => {
        // 在 preScoreData 中查找与当前 item.id 对应的 areaId
        let matchingPreScore = undefined
        if (type === 'update') {
          matchingPreScore = preScoreData.find(
            (preScore: any) => preScore.areaId === item.id
          );
        }

        allAreaScore.value += item.score

        return {
          id: matchingPreScore ? matchingPreScore.id : "",
          areaId: item.id,
          projectId: projectId,
          assessmentBatchId: assessmentBatchId,
          areaDetailId: matchingPreScore ? matchingPreScore.areaDetailId : item.areaDetailDOList[0].id,
          checkType: checkType,
          remark: matchingPreScore ? matchingPreScore.remark : "",
        };
      });
    }
    updateTotalScore() // 初始化总分
  } finally {
    formLoading.value = false
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件
const submitForm = async () => {
  try {
    await scoreFormRef.value?.validate()
    formLoading.value = true
    if (formType.value === 'create') {
      // await ProjectApi.createCheckRecord(submitFormData.value)
      // message.success(t('common.createSuccess'))
    } else {
      // await ProjectApi.updateCheckRecord(submitFormData.value)
      // message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success', submitFormData.value, totalScore, allAreaScore)
  } catch (error) {
    console.error(error)
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = []
  submitFormData.value = []
  totalScore.value = 0
  scoreFormRef.value?.resetFields()
}
</script>
